<template>
    <el-container>
        <el-aside width="200px" v-loading="showGrouploading">
            <el-container>
                <el-header>
                    <el-input :placeholder="$t('user.filterText')" v-model="groupFilterText" clearable></el-input>
                </el-header>
				<el-main class="nopadding">
					<el-tree ref="groupRef" class="menu" node-key="id" :data="group" :props="groupsProps" :current-node-key="''" :highlight-current="true" :expand-on-click-node="false" :filter-node-method="groupFilterNode" @node-click="groupClick"></el-tree>
				</el-main>
			</el-container>
		</el-aside>
		<el-container>
				<el-header>
					<div class="left-panel">
						<el-button v-auth="'user.add'" type="primary" icon="el-icon-plus" @click="add"></el-button>
						<el-button v-auth="'user.delete'" type="danger" plain icon="el-icon-delete" :disabled="selection.length==0" @click="batch_del"></el-button>
						<el-button v-auth="'user.allot'" type="primary" plain :disabled="selection.length==0">{{ $t('user.roleAllot') }}</el-button>
						<el-button v-auth="'user.reset'" type="primary" plain :disabled="selection.length==0" @click="reset_password">{{ $t('user.resetPassword') }}</el-button>
					</div>
					<div class="right-panel">
						<div class="right-panel-search">
							<el-input v-model="search.name" :placeholder="$t('user.searchName')" clearable></el-input>
							<el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
						</div>
					</div>
				</el-header>
				<el-main class="nopadding">
					<scTable ref="tableRef" :apiObj="apiObj" @selection-change="selectionChange" stripe remoteSort remoteFilter>
						<el-table-column type="selection" :selectable="isRowSelectable" width="50"></el-table-column>
						<el-table-column label="ID" prop="id" width="80" sortable='custom'></el-table-column>
						<el-table-column :label="$t('user.table.avatar')" width="80" column-key="filterAvatar" :filters="[{text: $t('user.table.uploaded'), value: '1'}, {text: $t('user.table.unuploaded'), value: '0'}]">
							<template #default="scope">
								<el-avatar :src="scope.row.avatar" size="small"></el-avatar>
							</template>
						</el-table-column>
						<el-table-column :label="$t('user.table.username')" prop="username" width="150" sortable='custom' column-key="filterUserName" :filters="[{text: $t('user.table.systemUsername'), value: '1'}, {text: $t('user.table.generalUsername'), value: '0'}]"></el-table-column>
						<el-table-column :label="$t('user.table.name')" prop="name" width="100" sortable='custom'></el-table-column>
						<el-table-column v-auth="'user.state'" :label="$t('common.status')" prop="status" width="80">
							<template #default="scope">
								<el-switch v-model="scope.row.status" @change="changeSwitch($event, scope.row)" :disabled="scope.row.id === 1" :loading="scope.row.$switch_status" :active-value="1" :inactive-value="0"></el-switch>
							</template>
						</el-table-column>
						<el-table-column :label="$t('user.table.rule')" prop="role_names" width="200" sortable='custom'></el-table-column>
						<el-table-column :label="$t('common.time')" prop="create_at" width="170" sortable='custom'></el-table-column>
						<el-table-column :label="$t('common.operate')" fixed="right" align="center" width="180">
							<template #default="scope">
								<el-button-group>
									<el-button v-auth="'user.reset'" text type="primary" size="small" @click="table_modify(scope.row, scope.$index)">{{ $t('user.password') }}</el-button>
									<el-button v-auth="'user.edit'" text type="primary" size="small" @click="table_edit(scope.row, scope.$index)">{{ $t('common.edit') }}</el-button>
									<el-popconfirm :title="$t('common.confirmRemove')" @confirm="table_del(scope.row, scope.$index)">
										<template #reference>
											<el-button v-auth="'user.delete'" :disabled="scope.row.id === 1" text type="primary" size="small">{{ $t('common.del') }}</el-button>
										</template>
									</el-popconfirm>
								</el-button-group>
							</template>
						</el-table-column>
					</scTable>
				</el-main>
		</el-container>
	</el-container>
	<save-dialog v-if="dialog.save" ref="saveDialogRef" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
	<password-dialog v-if="dialog.password" ref="passwordDialogRef" @success="handleSuccess" @closed="dialog.password=false"></password-dialog>
</template>
<script setup>
import { ref, reactive, watch, onMounted, nextTick } from 'vue';
import api from '@/api';
import i18n from '@/locales';
import { ElMessage, ElMessageBox } from 'element-plus';
import saveDialog from './save.vue';
import passwordDialog from './password.vue';

// 定义响应式数据
const dialog = reactive({
  save: false,    // 控制保存对话框的显示
  password: false // 控制密码对话框的显示
});
const groupRef = ref(null); // 引用树形组件
const tableRef = ref(null); // 引用表格组件
const showGrouploading = ref(false);
const groupFilterText = ref('');
const group = ref([]);
const selection = ref([]);
const search = reactive({
  name: null
});
const groupsProps = reactive({
    value: "id",
    label: "name",
});
const saveDialogRef = ref(null);
const passwordDialogRef = ref(null);
const apiObj = ref(api.setting.user.list);
// 监听组过滤文本变化
watch(groupFilterText, (val) => {
    groupRef.value.filter(val); // 过滤树形控件的节点
});
// 组件挂载时加载数据
onMounted(() => {
    getGroup(); // 加载树形控件的数据
});
// 定义添加用户的方法
const add = () => {
    dialog.save = true;
    nextTick(() => {
        saveDialogRef.value.open();
    });
};
// 定义编辑用户的方法
const table_edit = (row) => {
    dialog.save = true;
    nextTick(() => {
        saveDialogRef.value.open('edit');
		saveDialogRef.value.setData(row);
    });
};
// 定义修改密码的方法
const table_modify = (row) => {
    dialog.password = true;
    nextTick(() => {
        passwordDialogRef.value.open('modify');
		passwordDialogRef.value.setData(row);
    });
};
// 定义重置密码的方法
const reset_password = () => {
	const ids = selection.value.map(item=> item.id);
    dialog.password = true;
	nextTick(() => {
		passwordDialogRef.value.open('reset', ids);
	});
};
// 定义删除的方法
const table_del = async (row, index) => {
    const reqData = {ids: [row.id]};
    const res = await api.setting.user.delete.delete(reqData);
    if(res.code == 200) {
        // 这里选择刷新整个表格 OR 插入/编辑现有表格数据
        tableRef.value.tableData.splice(index, 1);
        ElMessage.success(res.message);
    } else {
        ElMessage.error(res.message);
    }
};
// 定义批量删除的方法
const batch_del = () => {
    ElMessageBox.confirm(i18n.global.t('common.confirmDelete', { count: selection.value.length }), i18n.global.t('common.tip'), {
        type: 'warning',
    }).then(async () => {
        const ids = selection.value.map(item => item.id);
        const res = await api.setting.user.delete.delete({ids});
        if (res.code == 200) {
			selection.value.forEach(item => {
				tableRef.value.tableData.forEach((itemI, indexI) => {
					if (item.id === itemI.id) {
						tableRef.value.tableData.splice(indexI, 1);
					}
				})
			})
            ElMessage.success(res.message);
        } else {
            ElMessage.error(res.message);
        }
    })
};
// 表格选择后回调事件
const selectionChange = (val) =>  selection.value = val;
// 禁止选择ID为1的用户
const isRowSelectable = (row) => row.id !== 1;
// 表格内开关
const changeSwitch = (val, row) => {
	row.status = val;
	row.$switch_status = true;
    setTimeout(async () => {
		try {
			const res = await api.setting.user.state.put({id:row.id, status:row.status});
			if (res.code == 200) {
				delete row.$switch_status;
				ElMessage.success(res.message);
			} else {
				ElMessage.error(res.message);
			}
		} catch (error) {
			console.error('Error in setting/user/index/changeSwitch action:', error);
		} finally {
			row.$switch_status = false;
		}
    }, 500);
};
// 加载树数据
const getGroup = async () => {
    try {
		showGrouploading.value = true;
        const res = await api.setting.dept.list.get();
		if (res.code == 200) {
			var allNode ={id: 0, name: '所有'};
			res.data.unshift(allNode);
			group.value = res.data;
		}
    } catch (error) {
        console.error('Error in setting/user/index/getGroup action:', error);
    } finally {
        showGrouploading.value = false;
    }
};
// 树过滤
const groupFilterNode = (value, data) => {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
};
// 树点击事件
const groupClick = (data) => {
    var params = { dept_id: data.id };
    tableRef.value.reload(params);
};
// 搜索
const upsearch = () => tableRef.value.upData(search);
// 本地更新数据
const handleSuccess = (data, mode) => {
    if (mode == 'add') {
		tableRef.value.refresh();
    } else if (mode =='edit') {
		tableRef.value.refresh();
    }
};
</script>